import sys
import pygame

from settings import Settings
from rocket import Rocket

class RocketGame:
    def __init__(self):
        """初始化游戏并创建游戏资源"""
        pygame.init()
        # 控制帧率
        self.clock = pygame.time.Clock()

        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width,
                                               self.settings.screen_height))
        
        pygame.display.set_caption("Rocket Game")

        #设置背景颜色
        self.bg_color = (self.settings.bg_color)

        self.rocket = Rocket(self)


    
    def run_game(self):
        while True:

            self._check_events()
            self.rocket.update()
            self._update_screen()
            
            self.clock.tick(60)     #游戏帧率设为60


    def _check_events(self):
            # 侦察键盘和鼠标事件
            # pygame.event.get()访问检测到的事件
            for event in pygame.event.get():   
                if event.type == pygame.QUIT:
                    sys.exit()

                    #每当用户按键时，都在Pygame中产生一个KEYDOWN事件
                elif event.type == pygame.KEYDOWN:
                   self._check_keydown_events(event)
                # 玩家释放按键时
                elif event.type == pygame.KEYUP:    
                   self._check_keyup_events(event)


    def _check_keydown_events(self,event):
        """响应按下"""
        if event.key == pygame.K_RIGHT:    #右方向键(pygame.K_RIGHT)
            # 向右移动火箭
            self.rocket.moving_right = True
        elif event.key == pygame.K_LEFT:
            # 向左移动火箭
            self.rocket.moving_left = True
        elif event.key == pygame.K_UP:
            # 向上移动火箭
            self.rocket.moving_up = True
        elif event.key == pygame.K_DOWN:
            # 向下移动火箭
            self.rocket.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self,event):
        """响应释放"""
        if event.key == pygame.K_RIGHT:
            self.rocket.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.rocket.moving_left = False
        if event.key == pygame.K_UP:
            self.rocket.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.rocket.moving_down = False

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)

        # 将火箭绘制在屏幕上
        self.rocket.blitme()

        pygame.display.flip()


if __name__ == '__main__':
    r = RocketGame()
    r.run_game()